package com.senthink.gl.business.common.util;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.Optional;

/**
 * Page相关的工具类
 *
 * @author zooqi@senthink.com
 * @date 2018/01/04
 */
public final class PageUtils {

    /**
     * 只有一条记录的Page
     */
    public static final PageRequest PAGE_SINGLE_RECORD = new PageRequest(0, 1);

    private PageUtils() {
    }

    /**
     * 获取{@link Page}当前页中单个记录
     *
     * @param page
     * @param <T>
     * @return
     */
    public static <T> Optional<T> fetchSingle(Page<T> page) {
        if (page == null || page.getTotalElements() == 0 || page.getContent().isEmpty()) {
            return Optional.empty();
        }
        return Optional.ofNullable(page.getContent().get(0));
    }
}
